unit UEditItems;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons,
// selfmade units
  uConfig, uItems, uUtils;


type
  TfrmEditItem = class(TForm)
    BtnOK: TBitBtn;
    BtnCancel: TBitBtn;
    procedure BtnOKClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    CurItemId: Integer;
    ItemControls: array[NItemParam] of THackControl;
  public
    function Add(): TModalResult;
    function Edit(Index: Integer): TModalResult;
  end;

var
  frmEditItem: TfrmEditItem;

implementation

{$R *.dfm}

function TfrmEditItem.Add(): TModalResult;
begin
  Result := Edit(ItemConfig.Add);
end;

procedure TfrmEditItem.BtnOKClick(Sender: TObject);
var
  i: NItemParam;
begin
  for i := Low(NItemParam) to High(NItemParam) do
    ItemConfig.Items[CurItemId, i] := ItemControls[i].Text;
end;


function TfrmEditItem.Edit(Index: Integer): TModalResult;
var
  I: NItemParam;
begin
  CurItemId := Index;
  for i := Low(NItemParam) to High(NItemParam) do
  begin
    if (Trim(ItemConfig.Items[Index, i]) <> '') then
      ItemControls[i].text := ItemConfig.Items[Index, i];
  end;
  Result := ShowModal;
end;

procedure TfrmEditItem.FormCreate(Sender: TObject);
const
  middle = NItemParam(Ord(High(NItemParam)) div 2); 
var
  I: NItemParam;  
  T, L: Integer;
begin
  T := 0; L := 0;
  ClientWidth := (Ord(High(NItemParam)) div Ord(Middle)) * 300;
  ClientHeight := Ord(Middle) * 30 + 90;
  for i := Low(NItemParam) to High(NItemParam) do
  begin
    with TLabel.Create(Self) do
    begin
      Top := Ord(T) * 30 + 4;
      Left := L;
      Parent := Self;
      Caption := ItemParamNames[i];
    end;
    TControl(ItemControls[i]) := ControlTypes[ItemParamType[i]].Create(Self);
    with ItemControls[i] do
    begin
      case ItemParamType[I] of
        npString: Width := 192;
      end;
      Top := Ord(T) * 30;
      Left := L + 100;
      Tag := Ord(i);
      Parent := Self;
      if i in [ipID] then Enabled := False;
    end;
    if (T = Ord(Middle)) then
    begin
      T := 0;
      Inc(L, 300);
    end else Inc(T);
  end;
end;

end.
